package net.hiwii.db.bind.map;

import java.util.ArrayList;
import java.util.List;

import com.sleepycat.bind.tuple.TupleBinding;
import com.sleepycat.bind.tuple.TupleInput;
import com.sleepycat.bind.tuple.TupleOutput;

import net.hiwii.arg.Argument;
import net.hiwii.cognition.Expression;
import net.hiwii.db.ent.MappingFormat;
import net.hiwii.system.util.StringUtil;

/**
 * type = f; functionDeclaration
 * type = c; conditionDeclaration
 * @author Administrator
 *
 */
public class  MappingFormatBinding extends TupleBinding<MappingFormat> {
	@Override
	public MappingFormat entryToObject(TupleInput arg0) {
		MappingFormat fd = new MappingFormat();
//		FunctionFormat ff = new FunctionFormat();
		String name = arg0.readString();
		
		int num = arg0.readInt();
//		Map<String, String> map = new HashMap<String, String>();
		List<Argument> arguments = new ArrayList<Argument>();
		for(int n=0;n<num;n++){
			Argument arg = new Argument();
			String argname = arg0.readString();
			String type = arg0.readString();
			//read condition limits
			int l = arg0.readInt();
			if(l > 0) {
				List<Expression> limits = new ArrayList<Expression>();
				for(int m=0;m<l;m++){					
					String cond = arg0.readString();
					Expression expr = StringUtil.parseString(cond);
					limits.add(expr);
				}
				arg.setLimits(limits);
			}else {
				arg.setLimits(null);
			}
			
			arg.setName(argname);
			arg.setType(type);
			arguments.add(arg);
		}
		fd.setName(name);
		fd.setArguments(arguments);
		return fd;
	}

	@Override
	public void objectToEntry(MappingFormat arg0, TupleOutput arg1) {
		arg1.writeString(arg0.getName());
		arg1.writeInt(arg0.getArguments().size());
		
		for (Argument arg: arg0.getArguments()) {
			arg1.writeString(arg.getName());
			arg1.writeString(arg.getType());
			int l = 0;
			if(arg.getLimits() != null) {
				l = arg.getLimits().size();
			}
			if(l > 0) {
				arg1.writeInt(l);
				for(Expression expr:arg.getLimits()) {
					arg1.writeString(expr.toString());
				}
			}else {
				arg1.writeInt(0);
			}
		}
	}
}
